<?php
// +----------------------------------------------------------------------
// | 用户 模型
// +----------------------------------------------------------------------
namespace app\library\model;
use think\Model;

class User extends Model{
    /**
     * 删除用户
     * @param array $id 节点ID
     * @return bool
     */
    public function del($ids = '') {
        if (is_array($ids)) {
            $error = '';
            foreach ($ids as $k => $v) {
                $map = [];
                $map['id'] = $v;
                self::where($map)->delete();
            }
            if ($error) {
                $this->error = $error;
                return false;
            }
            return true;
        }
        $this->error = '参数传递错误';
        return false;
    }
    /**
     * 修改用户状态
     * @param $map
     * @param $val
     * @return bool|int
     */
    public function status($map,$val){
        $res = self::where($map)->setField('status', $val);
        return $res ? $res : false;
    }
    /**
     * 判断是否登录
     * @return bool|array
     */
    public function isLogin()
    {
        $user = cookie('member_user');
        if (isset($user['uid'])) {
            if (!self::where('id', $user['uid'])->find()) {
                return false;
            }
            return cookie('member_user_sign') == $this->dataSign($user) ? $user : false;
        }
        return false;
    }
    /**
     * 用户登录
     * @param string $username 用户名
     * @param string $password 密码
     * @return bool|mixed
     */
    public function login($card = '', $password = '')
    {
        $card = trim($card);
        $password = trim($password);
        $map = [];
        $map['status'] = 1;
        $map['card_id'] = $card;
        if ($this->validateData(input('post.'), 'User.login') != true) {
            $this->error = $this->getError();
            return false;
        }
        $user = self::where($map)->find();
        if (!$user) {
            $this->error = '用户不存在或被禁用！';
            return false;
        }
        // 密码验证
        if (md5($password) != $user->password) {
            $this->error = '登陆密码错误！';
            return false;
        }
        // 执行登陆
        $login = [];
        $login['uid'] = $user->id;
        $login['group'] = $user->group;
        $login['name'] = $user->name;
        // 缓存登录信息
        cookie('member_user', $login);
        cookie('member_user_sign', $this->dataSign($login));
        return $user->id;

    }
    /**
     * 数据签名认证
     * @return string
     */
    public function dataSign($data = [])
    {
        if (!is_array($data)) {
            $data = (array) $data;
        }
        ksort($data);
        $code = http_build_query($data);
        $sign = sha1($code);
        return $sign;
    }
    /**
     * 退出登陆
     * @return bool
     */
    public function logout()
    {
        cookie('member_user', null);
        cookie('member_user_sign', null);
    }
}